import cv2

def display_stream(url):
    # 创建视频捕获对象
    cap = cv2.VideoCapture(url)
    
    # 检查流是否成功打开
    if not cap.isOpened():
        print(f"无法打开视频流: {url}")
        return
    
    print("按 'q' 键退出程序")
    
    cascade_path = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
    face_cascade = cv2.CascadeClassifier(cascade_path)
    if face_cascade.empty():  
        print('Haar 级联模型加载失败，请检查路径是否正确')  
        return
    
    while True:
        # 读取帧
        ret, frame = cap.read()
        
        if not ret:
            print("无法获取帧，可能流已结束或中断...")
            break

        #将当前帧转换为灰度图  
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #在当前帧上检测人脸
        faces = face_cascade.detectMultiScale(  
            gray,  
            scaleFactor=1.1,  
            minNeighbors=5,  
            minSize=(30, 30)  
        )
        #将检测到的人脸用矩形框标注
        for (x, y, w, h) in faces:  
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        
        # 显示帧
        cv2.imshow('视频流', frame)
        
        # 按'q'退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    # 示例URL（替换为你实际的流地址）
    stream_urls = [
        "http://192.168.2.26:4747/video",
        "rtsp://example.com/live/stream",  # RTSP示例
        "rtmp://example.com/live/stream",  # RTMP示例
        "http://example.com/stream.m3u8",  # HLS示例
        "http://example.com/video.mp4"     # HTTP视频示例
    ]
    
    # 使用第一个URL（可以修改为你想测试的URL）
    url = stream_urls[0]
    display_stream(url)